package com.google.code.mergeinformer.model;

import com.google.code.mergeinformer.constraint.CvsUrl;
import com.google.code.mergeinformer.constraint.Group;
import com.google.code.mergeinformer.constraint.Reachable;
import com.google.code.mergeinformer.util.AppUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import javax.validation.constraints.Size;

@Embeddable
@Reachable(groups = Group.Live.class)
public class VcsAttributes {

    private static final Logger log = LoggerFactory.getLogger(VcsAttributes.class);

    private static final String DEFAULT_USERNAME = AppUtils.getProperty("app.svn.username");
    private static final String DEFAULT_PASSWORD = AppUtils.getProperty("app.svn.password");

    @NotBlank
    @Size(max = 255)
    @CvsUrl
    @Column(name = "base_url", nullable = false)
    private String url;

    @Column(name = "auth_type", nullable = false)
    @Enumerated(EnumType.STRING)
    private AuthType authType = AuthType.DEFAULT;

    @Column(name = "vcs_username")
    @Size(max = 255)
    private String username;

    @Column(name = "vcs_password")
    @Size(max = 255)
    private String password;

    public VcsAttributes() {
    }

    public VcsAttributes(VcsAttributes vcsAttributes) {
        url = vcsAttributes.url;
        authType = vcsAttributes.authType;
        username = vcsAttributes.username;
        password = vcsAttributes.password;
    }

    @PrePersist
    private void setCredentials() {
        if (authType != AuthType.CUSTOM) {
            username = null;
            password = null;
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public AuthType getAuthType() {
        return authType;
    }

    public void setAuthType(AuthType authType) {
        this.authType = authType;
    }

    public String getUsername() {
        switch (authType) {
            case DEFAULT:
                return DEFAULT_USERNAME;
            case ANONYMOUS:
                return null;
            case CUSTOM:
                return username;
            default:
                log.error("Unexpected value of " + AuthType.class + " inside switch statement");
                throw new RuntimeException();
        }
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        switch (authType) {
            case DEFAULT:
                return DEFAULT_PASSWORD;
            case ANONYMOUS:
                return null;
            case CUSTOM:
                return password;
            default:
                log.error("Unexpected value of " + AuthType.class + " inside switch statement");
                throw new RuntimeException();
        }
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
